<template>
  <select-cascader
    :value="value"
    :fetch-data="fetchData"
    :top-value="topVal"
    :bottom-level="bottomLevel"
    :props="props"
    :structure="structure"
    :placeholder="placeholder"
    v-bind="$attrs"
    @change="handleChange"
  ></select-cascader>
</template>
<script>
import SelectCascader from './SelectCascader'

export default {
  components: {
    SelectCascader,
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  props: {
    value: String,
    topValue: { type: String, default: '' },
    bottomLevel: Number, // 从顶级(topValue)开始为0
    autoTop: { type: Boolean, default: false }, // 是否自动用当前用户的组织地址作为第一级
  },
  data() {
    return {
      props: { value: 'id', label: 'geoName', children: 'children' },
      structure: [2, 2, 2, 3, 3],
    }
  },
  computed: {
    topVal() {
      return this.autoTop ? this.$utils.getAddressCode() : this.topValue
    },
    placeholder() {
      return (this.$attrs && this.$attrs.placeholder) || '请选择地区'
    },
    levelLength() {
      return this.structure.reduce((v, o) => v + o, 0)
    },
    hasUserId() {
      return !!this.$utils.getUserId()
    },
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    handleChange(val, label) {
      this.$emit('change', val, label)
    },
    fetchData(value, level) {
      // api需要权限，但很快
      if (this.hasUserId) {
        const nextLevel = level + 1
        const params = {
          'region_lever.eq': nextLevel,
        }
        if (value) {
          const { levelLength, structure } = this
          const cutCount = levelLength - structure.slice(0, nextLevel).reduce((p, c) => p + c, 0)
          let nextValue = Number.parseInt(value, 10) / Math.pow(10, cutCount) + 1
          nextValue = `${nextValue}${Array(cutCount + 1).join('0')}`

          params['id.gt'] = value
          params['id.lt'] = nextValue
          params['region_lever.eq'] = nextLevel + 1
        }
        return this.$api.getData('industrial_db', 'geo_codings', params).then(res =>
          (res.data || []).map(item => ({
            geoName: item.geo_name,
            id: item.id,
          }))
        )
      }

      // api不需要权限，但很慢
      return this.$http.get(`/industrial/geo/tree?addressCode=${value}`).then(res => res.data || [])
    },
  },
}
</script>
<style scoped></style>
